<template>
  <el-card class="app-container">
    <!-- <div class="header_title_box">
      <h2>销售订单管理</h2>
    </div> -->
    <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'orderRecords@save'" size="small" type="success" icon="el-icon-circle-plus" @click="addOrder">新增订单</el-button>
        <el-button v-action="'orderRecords@orderImport'" size="small" type="primary" @click="productImport">导入</el-button>
        <el-button v-action="'orderRecords@export'" size="small" :disabled="data.length?false:true" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        <el-button v-action="'deliveryOrder@ordersDeliver'" size="small" type="primary" :disabled="selectedIds.length?false:true" @click="getorderdelivery">批量发货</el-button>
        <el-button v-action="'orderRecords@orderInvalidMore'" size="small" type="danger" :disabled="selectedIds.length?false:true" @click="getorderDelete">批量作废</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="small" class="filter-item" icon="el-icon-refresh" @click="handleRefresh">
          重置
        </el-button>
        <el-button size="small" @click="isActive=!isActive">{{ isActive?'展开':'收起' }}</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="data" :row-class-name="tableRowClassName" style="width: 100%;margin-bottom: 20px;" :max-height="screenHeigh" row-key="id" border default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @selection-change="handleSelectMulti">
      <el-table-column type="selection" width="55" :selectable="checkSelectable" />
      <el-table-column label="序号" type="index" width="55" align="center" fixed />
      <el-table-column align="center" label="操作" width="200" fixed>
        <template slot-scope="sales">
          <span v-if="(sales.row.status==1 && sales.row.logistics_status===0 && sales.row.after_have === 0 && sales.row.after_num1 === 0 && sales.row.after_num2 === 0 && sales.row.after_num3 === 0 && sales.row.after_num4 === 0 && sales.row.after_num5 === 0)" v-action="'orderRecords@update'" class="edit_style el-icon-edit-outline" @click="handleUpdateNewPath(sales.row.id)" />
          <span v-if="sales.row.status!==6&&sales.row.status!==10 && sales.row.after_have === 0 && sales.row.after_refund_all === 0" v-action="'orderRecords@createdAfterSale'" class="edit_style" @click="afterSale(sales)">申请售后</span>
          <span v-if="sales.row.print_delivery_num===0 && sales.row.status !== 6&& sales.row.after_have === 0 && sales.row.after_num1 === 0 && sales.row.after_num2 === 0 && sales.row.after_num3 === 0 && sales.row.after_num4 === 0 && sales.row.after_num5 === 0" v-action="'orderRecords@invalid'" class="delete_style" @click="handleInvalid('/orderRecords/invalid', sales.row.id)">作废</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="id" sortable label="ID" width="100" />
      <el-table-column align="center" sortable prop="status_text" label="状态" />
      <!-- print_delivery_num -->
      <el-table-column align="center" prop="print_delivery_num" label="已打印发货单" />
      <el-table-column align="center" prop="platform" sortable label="平台" width="100" />
      <el-table-column align="center" prop="order_no" sortable label="订单编号" width="150">
        <template slot-scope="scope">
          <span class="pointer blue" @click="$router.push({path: `/order/orderInfo/${scope.row.id}`, query: { title: '销售订单' }})">{{ scope.row.order_no }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="platform_no" sortable label="平台订单编号" width="180" show-overflow-tooltip />
      <!-- platform_no_ext -->
      <el-table-column align="center" prop="platform_no_ext" sortable label="平台订单编号2" width="180" show-overflow-tooltip />
      <el-table-column align="center" prop="shop_name" sortable label="店铺" width="150" />
      <el-table-column align="center" prop="goods_code" sortable label="系统sku" min-width="180" />
      <!-- sku -->
      <el-table-column align="center" prop="sku" sortable label="平台sku" min-width="180" />
      <el-table-column align="center" prop="name_ch" sortable label="中文名称" width="150" show-overflow-tooltip />
      <el-table-column align="center" prop="address_name" label="买家姓名" width="150" show-overflow-tooltip />
      <el-table-column align="center" prop="address_stateorprovince" label="州" />
      <el-table-column align="center" prop="address_cityname" label="城市" show-overflow-tooltip width="130" />
      <!-- <el-table-column align="center" prop="company_id" label="客户id" /> -->
      <el-table-column align="center" prop="order_source" label="订单来源" width="120">
        <template slot-scope="scope">
          <!-- 0-平台接口;1-录入;2-导入 -->
          {{ scope.row.order_source===1 ? '录入': scope.row.order_source===2 ? '导入':'平台拉取' }}
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="after_sale_status" label="是否存在售后" width="140">
        <template slot-scope="scope">
          {{ scope.row.after_sale_status === 0 ? '否' : '是' }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="get_at" sortable label="订单拉取时间" width="165" />
      <el-table-column align="center" prop="creator_username" label="创建人" width="112">
        <template slot-scope="scope">
          <app-text :text="scope.row.creator_username" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" sortable label="创建时间" width="165" />
      <el-table-column align="center" prop="category_text" sortable label="分类" show-overflow-tooltip />
      <el-table-column align="center" prop="address_email" label="买家邮箱" width="150" show-overflow-tooltip />
      <el-table-column align="center" prop="updater_username" label="修改人" width="112">
        <template slot-scope="scope">
          <app-text :text="scope.row.updater_username" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updated_at" sortable label="修改时间" width="165" />
    </el-table>
    <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[50,100,200,500]" :page-size="queryParam.limit" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <!-------- 回到顶部 ------------>
    <el-backtop :visibility-height="200">
      <i class="el-icon-caret-top" />
    </el-backtop>
    <!--下载字段选择-->
    <DownModul :url="downloadxlsxUrl" :search-param="downLoadParams" :form-visible-down.sync="formVisibleDown" titel="导出字段选择" :options-modul="optionsModul" />
    <!-- 申请售后 -->
    <ApplySales :id.sync="orderId" :shop-id="shopId" :status.sync="status" :form-visible-down.sync="formVisibleAfterSale" titel="申请售后" @handleSearch="handleSearch" />
    <!-- 导入 -->
    <import-dialog url="/orderRecords/import" title="导入订单" :form-visible.sync="importDialogVisible" @download="downLoad" @handleRefresh="handleRefresh" />
    <!-- 销售订单批量发货 -->
    <DeliverGoods title="销售订单批量发货" :form-visible-deliver.sync="formVisibleDeliver" :ids="selectedIds" :codes="selectedCodes" @handleSearch="handleSearch" />
    <el-dialog :center="true" title="销售订单批量作废" :visible.sync="formVisibleDelete" width="700px">
      <div class="from_box">
        <el-form ref="ruleForm" label-width="140px" class="demo-ruleForm">
          <el-form-item :label="`已选择订单(${selectedCodes.length}个):`">
            {{ selectedCodes }}
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align: center;">确定作废吗？</div>
      <div style="text-align: center;margin-top:20px;">
        <el-button type="primary" :loading="isbtn" @click="submitDelete">确定</el-button>
        <el-button @click="formVisibleDelete = false">取消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import {
  action
} from '@/directive/permission/index.js' // 权限判断指令
import DownModul from '@/components/DownModul/index.vue'
import ApplySales from '@/components/applySales/index.vue'
import importDialog from '@/components/importDialog/index'
import { downloadStream } from '@/utils/index'
import appText from '@/components/appText/index'
import FormSelections from '@/components/FormSelection'
import DeliverGoods from '@/components/DeliverGoods/index.vue'
export default {
  name: 'OrderRecords',
  directives: {
    action
  },
  components: { DownModul, ApplySales, importDialog, appText, FormSelections, DeliverGoods },
  mixins: [formOperate],
  data() {
    return {
      otherHeight: 405,
      secondUrl: 1, // 二级路由
      isbtn: false,
      ids: '',
      formVisibleDeliver: false,
      formVisibleDelete: false,
      searchClass: 1,
      searchShop: 1,
      formItems: [
        {
          label: '订单编号',
          key: 'order_no',
          type: 'input',
          placeholder: '请输入订单编号'
        },
        {
          label: '平台名称',
          key: 'platform_name',
          type: 'input',
          placeholder: '请输入平台'
        },
        {
          label: '店铺',
          key: 'shop_id',
          type: 'select',
          multiple: true,
          filterable: true,
          placeholder: '请选择店铺',
          options: []
        },
        // {
        //   label: '按照邮编',
        //   key: 'postalcode',
        //   type: 'input',
        //   placeholder: '请输入邮编'
        // },
        {
          label: '系统SKU',
          key: 'goods_code',
          type: 'input',
          placeholder: '请输入系统SKU'
        },
        {
          label: '中文名称',
          key: 'name_ch',
          type: 'input',
          placeholder: '请输入中文名称'
        },
        {
          label: '商品分类',
          key: 'category_ids',
          type: 'cascader',
          cLabel: 'lable',
          cValue: 'value',
          options: []
        },
        {
          label: '订单状态',
          key: 'status',
          type: 'select',
          options: [
            {
              label: '待发货',
              value: '1'
            },
            {
              label: '发货中',
              value: '2'
            },
            {
              label: '已发货',
              value: '3'
            },
            {
              label: '作废订单',
              value: '6'
            }
          ]
        },
        {
          label: '订单来源',
          key: 'order_source',
          type: 'select',
          options: [
            {
              label: '平台拉取',
              value: '0'
            },
            {
              label: '录入',
              value: '1'
            },
            {
              label: '导入',
              value: '2'
            }
          ]
        },
        {
          label: '买家州/省',
          key: 'state',
          type: 'input',
          placeholder: '请输入州'
        },
        {
          label: '买家城市',
          key: 'city_name',
          type: 'input',
          placeholder: '请输入城市'
        },
        {
          label: '买家姓名',
          key: 'user_name',
          type: 'input',
          placeholder: '请输入买家姓名'
        },
        {
          label: '买家邮箱',
          key: 'email',
          type: 'input',
          placeholder: '请输入邮箱'
        },
        {
          label: '拉取日期',
          key: 'date',
          type: '',
          //   valueFormat: 'timestamp',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        },
        {
          label: '生成日期',
          key: 'dateCreat',
          type: '',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      payDate: [],
      componentName: 'OrderRecords',
      cachePaths: [
        '/order/orderInfo',
        '/order/orderAdd'
      ],
      downloadxlsxUrl: '/orderRecords/export',
      importDialogVisible: false,
      shopId: '',
      status: '',
      orderId: '',
      formVisibleAfterSale: false,
      formVisibleDown: false,
      loading: false,
      select: 'shop_name',
      formName: 'orderRecords',
      formLabelWidth: '90px',
      // 刷新路由
      refreshRoute: true,
      queryParam: {
        start_at: '',
        end_at: '',
        status: '1',
        type: 0,
        abnormal: '0',
        start_at_pay: '',
        end_at_pay: '',
        page: 1,
        limit: 50
      },
      fiftyLimit: 50,
      defaultQueryParam: ['type', 'abnormal'],
      // type
      url: 'orderRecords',
      optionsModul: [
        {
          key: 'order_ids',
          label: '订单ID'
        },
        {
          key: 'order_no',
          label: '订单编号'
        },
        {
          key: 'platform_no',
          label: '平台订单编号'
        },
        {
          key: 'platform',
          label: '平台名称'
        },
        {
          key: 'shop_name',
          label: '店铺名称'
        },
        {
          key: 'name_ch',
          label: '商品名称'
        },
        {
          key: 'category_names',
          label: '商品类别'
        },
        {
          key: 'goods_code',
          label: '系统SKU'
        },
        {
          key: 'sku',
          label: '平台SKU'
        },
        {
          key: 'quantity_purchased',
          label: '总个数'
        },
        {
          key: 'transaction_price_currencyid',
          label: '币别'
        },
        {
          key: 'total_amount',
          label: '总金额（含税）'
        },
        {
          key: 'tax_amount_value_all',
          label: '税费'
        },
        {
          key: 'status_text',
          label: '订单状态'
        },
        {
          key: 'company_name',
          label: '所属公司'
        },
        {
          key: 'address_name',
          label: '买家姓名'
        },
        {
          key: 'buyer_email',
          label: '买家邮箱'
        },
        {
          key: 'address_phone',
          label: '电话号码'
        },
        {
          key: 'address_postalcode',
          label: '邮编'
        },
        {
          key: 'address_country',
          label: '国家'
        },
        {
          key: 'address_stateorprovince',
          label: '州'
        },

        {
          key: 'address_cityname',
          label: '城市'
        },

        {
          key: 'address_street1',
          label: '街道'
        },

        {
          key: 'created_at',
          label: '订单生成时间'
        },

        {
          key: 'get_at',
          label: '订单拉取时间'
        },

        {
          key: 'shipped_at',
          label: '发货时间'
        }
      ]
    }
  },

  //   computed: {
  //     downLoadParams() {
  //       const params = {}
  //       const object = this.queryParam
  //       for (const key in object) {
  //         if (Object.hasOwnProperty.call(object, key)) {
  //           const element = object[key]
  //           params[key] = element
  //         }
  //       }
  //       return params
  //     }
  //   },
  methods: {
    addOrder() {
      window.localStorage.removeItem('saleOrder')
      window.localStorage.removeItem('saleOrderModel')
      this.$router.push({
        path: '/order/orderAdd',
        query: { title: '销售订单' }
      })
    },
    // 申请售后
    afterSale(sales) {
      this.formVisibleAfterSale = true
      this.orderId = sales.row.id + ''
      this.status = sales.row.status + ''
      this.shopId = sales.row.shop_basics_id + ''
    },
    // 导出
    handleExport() {
      const vm = this
      const params = {}
      const object = this.queryParam
      for (const key in object) {
        if (Object.hasOwnProperty.call(object, key)) {
          const element = object[key]
          params[key] = element
        }
      }
      //   vm.handleExportxlsx(vm.exportUrl, params)
      vm.downLoadParams = params
      vm.formVisibleDown = true
    },
    beforeSearch() {
      const vm = this
      vm.queryParam.start_at_pay = ''
      vm.queryParam.end_at_pay = ''
      vm.queryParam.start_at = ''
      vm.queryParam.end_at = ''
      vm.queryParam.start_at_creat = ''
      vm.queryParam.end_at_creat = ''
      vm.queryParam.shop_ids = ''
      if (vm.queryParam.date && vm.queryParam.date.length > 0) {
        vm.queryParam.start_at = vm.queryParam.date[0]
        vm.queryParam.end_at = vm.queryParam.date[1]
      }
      if (vm.queryParam.shop_id && vm.queryParam.shop_id.length > 0) {
        vm.queryParam.shop_ids = vm.queryParam.shop_id.join(',')
      }
      // 生成日期转化
      if (vm.queryParam.dateCreat && vm.queryParam.dateCreat.length > 0) {
        vm.queryParam.start_at_creat = vm.queryParam.dateCreat[0]
        vm.queryParam.end_at_creat = vm.queryParam.dateCreat[1]
      }
      if (vm.queryParam.category_ids && vm.queryParam.category_ids.length > 0) {
        const arr = vm.queryParam.category_ids
        vm.queryParam.category_id = arr[arr.length - 1]
      } else {
        vm.queryParam.category_id = ''
      }
    },
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/orderRecords/import/template', { responseType: 'blob' })
        .then((res) => {
          downloadStream(res, '订单导入模板.xlsx')
        })
    },
    // 导入
    productImport() {
      const vm = this
      vm.importDialogVisible = true
    },
    checkSelectable(row, index) {
      return row.status === 1 && row.logistics_status === 0 && row.after_num1 === 0 && row.after_have === 0
    },
    // 编辑
    handleUpdateNewPath(id) {
      const vm = this
      window.localStorage.removeItem('saleOrder')
      window.localStorage.removeItem('saleOrderModel')
      vm.$router.push({
        path: '/order/orderAdd',
        query: { title: '编辑订单', id: id }
      })
    },
    // 批量发货
    getorderdelivery() {
      const vm = this
      const list = this.data.filter((arr) => {
        return this.selectedIds.includes(arr.id) && arr.delivery_method === 0 && !arr.after_num1
      })
      const ids = list.map((arr) => {
        return arr.id
      })
      vm.selectedIds = ids
      vm.selectedCodes = list.map((arr) => {
        return arr.order_no
      })
      vm.formVisibleDeliver = true
      //   vm.ids = ids
      //   vm.$confirm(`确认批量发货订单${ids}`, '提示', {
      //     confirmButtonText: '确认',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     this.$http.post(`/deliveryOrder/ordersDeliver`, { ids: this.selectedIds }).then((res) => {
      //       this.$message.success('发货成功')
      //       this.handleSearch()
      //     }).catch(() => {})
      //   }).catch(() => {})
    },
    // 批量作废
    getorderDelete() {
      const vm = this
      const list = this.data.filter((arr) => {
        return this.selectedIds.includes(arr.id) && arr.print_delivery_num === 0
      })
      const ids = list.map((arr) => {
        return arr.id
      })
      vm.selectedIds = ids
      vm.selectedCodes = list.map((arr) => {
        return arr.order_no
      })
      vm.formVisibleDelete = true
    },
    submitDelete() {
      this.isbtn = true
      this.$http.post(`/orderRecords/orderInvalidMore`, { ids: this.selectedIds }).then(res => {
        if (res.code === 10000) {
          this.$message.success('操作成功')
          this.formVisibleDelete = false
          this.handleSearch()
          this.isbtn = false
        } else {
          this.isbtn = false
        }
      }).catch(() => {
        this.isbtn = false
      })
    }
  }
}
</script>
